<template>

  <el-dialog title="脚本生成" :close-on-click-modal="false" :close-on-press-escape="false" v-model="open"
    class="form-dialog  form-dialog-large" append-to-body v-loading="!loading">
    <el-form ref="generateForm" :model="form" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="账号ID">
            <el-select class="form-control" v-model="form.accountId" placeholder="请选择账号ID" filterable clearable  @change="onAccontChange">
                <el-option
                  v-for="(accountId, idx) in accountIds"
                  :key="idx"
                  :label="accountId"
                  :value="accountId"
                />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="账号偏好">
            <preference-panel v-model="preference" />
          </el-form-item>
        </el-col>
      </el-row>



      <el-row>
        <el-col :span="8">

          <el-form-item label="匹配分类">
            <el-checkbox-group v-model="form.matchSecondCategory">
              <el-checkbox-button :key="form.secondCategory" :value="form.secondCategory">
                {{ form.secondCategory }}
              </el-checkbox-button>
            </el-checkbox-group>

          </el-form-item>


        </el-col>
        <el-col :span="9">
          <el-form-item label="生成条数">
            <el-input-number :min="1" v-model="form.videoNumber" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="generateScriptText">生成脚本</el-button>
        </el-col>
        <el-col :span="3">
          <div class="generate-stats">
            <span class="text-error">{{ form.scriptText ? form.scriptText.split('\n').length :
              0}}</span> / {{ form.videoNumber }}
          </div>

        </el-col>

      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="脚本内容" prop="scriptText">
            <el-input type="textarea" v-model="form.scriptText" :rows="16" />
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>




    <template #footer>
      <div class="dialog-footer">
        <el-button :disabled="!form.scriptText" :id="'btn-copy-' + copyId">一键复制</el-button>
        <el-button :disabled="!form.scriptText" type="primary" @click="exportTxt">
          导出txt
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import * as accountService from '@/api/service/AccountService'
import * as categoryService from '@/api/service/CategoryService'
import * as selectionService from '@/api/service/SelectionService'
import PreferencePanel from '@/components/feishu/PreferencePanel.vue'

import { saveAs } from 'file-saver'
import ClipboardJS from 'clipboard';

const globalVal = globalThis as any;


defineOptions({ name: "GenerateForm" });

const emit = defineEmits(['update:show', 'success'])

const form: any = ref({
  trackText: '', // 跟单
  scriptText: '', // 新生成
  videoNumber: 20
})
const copyId = ref(new Date().getTime())
const loading = ref(false)
const open = ref(true)
const accountIds = ref<string[]>([])
const selections:any[] = <any>[];
const accounts:any[] = <any>[];
const preference = ref<any>(null)

function generateScriptText(): void {
  const records = form.value.records
  const record = form.value.record
  const matchUrls: string[] = []
  const recordUrls = getUrls(record);
  records.filter(item => {

    if (item[categoryService.FIRST_CATEGORY] != form.value.firstCategory) {
      return false;
    }

    if (form.value.matchSecondCategory.length > 0) {
      return form.value.matchSecondCategory.includes(item[categoryService.SECOND_CATEGORY])
    }

    return true;
  }).forEach(item => {
    const urls = getUrls(item);

    urls.forEach(url => {
      if (!recordUrls.includes(url) && !matchUrls.includes(url)) {
        matchUrls.push(url);
      }
    })
  })
  matchUrls.sort((a, b) => {
    void a
    void b
    return Math.random() - 0.5;
  })

  form.value.scriptText = matchUrls.slice(0, form.value.videoNumber).join('\n')
}

/**
 * 加载选品列表
 */
async function loadSelections(): Promise<any>{
  for await (const page of await selectionService.findList()){
    page.items.forEach(item => {
      const result = globalVal.parseFeishuRecord(item);
      const accountId = result['账号ID'];
      if( !accountIds.value.includes(accountId)){
        accountIds.value.push(accountId)
      }

      selections.push(result)
    })

  }
}

/**
 * 加载账号偏好表
 */
async function loadAccounts(): Promise<any>{
  for await (const page of await accountService.findList()){
    page.items.forEach(item => {
      const result = globalVal.parseFeishuRecord(item);
      accounts.push(result)
    })

  }
}

/**
 * 加载页面数据
 */
function loadData(){
  loading.value = true;
  Promise.all([loadSelections(),loadAccounts()]).finally(()=>{
    loading.value = false;
  })

}

function getUrls(record: any): string[] {
  const urls: string[] = []
  for (const key in record) {
    if (key.match('^跟单链接\\d+$')) {
      urls.push(record[key] as string)
    }
  }
  return urls
}

/**
 * 账号切换时
 */
function onAccontChange(): void {

  console.log(accounts)
  console.log(form.value.accountId)

}



/**
 * 导出文本
 */
function exportTxt(): void {
  const blob = new Blob([form.value.scriptText], { type: "text/plain;charset=utf-8" });
  saveAs(blob, '脚本文件.txt');
}





watch(open, (newVal) => {
  if (!newVal) {
    emit('update:show', false)
  }
})

onMounted(() => {

  const copyButtonId = "#btn-copy-" + copyId.value
  const clipboard = new ClipboardJS(copyButtonId, {
    text: () => {
      const codeStr = form.value.scriptText
      globalVal.success('复制成功')
      return codeStr
    }
  })
  clipboard.on('error', e => {
    console.log(e)
    globalVal.error('代码复制失败')
  })
})

loadData();

</script>
<style lang="scss" scoped>
.category-second {
  margin-left: 10px;
}

.commission {
  margin-right: 10px;
}
</style>
